<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link rel="icon" href="https://xlzy520.cn/icons/lo.ico">
  <meta name="referrer" content="no-referrer">
    <title>Drag</title>
    <style>
        html, body {
            margin: 0;
            padding: 0;
        }

        #dance {
            cursor: pointer;
        }
    </style>
</head>
<body ondrop="drop(event)" ondragover="allowDrop(event)" ontouchmove="drop(event)">
<div class="main">
    <img style="position: absolute;left: 0;top: 0;"
         src="https://profile.csdnimg.cn/4/5/4/0_qq_31201781"
         draggable="true" id="dance"
         width="200" ondragstart="drag(event)"
         ondrag="dragmove(event)"
         ontouchstart="drag(event)">
</div>
<script>
  (function () {
    document.getElementsByTagName('body')[0].style.height = window.innerHeight + 'px'
    document.getElementsByTagName('body')[0].style.width = window.innerWidth + 'px'
  })()
  let dance = document.getElementById('dance')
  let dragOffset={
    X1:null,
    Y1:null
  }

  function drag(e) {
    console.log(e);
    if (e.type === 'dragstart') {  //根据e.type判断是PC端还是移动端
      e = event ? event : e
    }else {
      if (event.touches) {
        e = event.touches[0] ? event.touches[0]:event;
      }
    }
    dragOffset.X1 = e.clientX - parseInt(dance.style.left)
    dragOffset.Y1 = e.clientY - parseInt(dance.style.top)
    // 鼠标点击的位置在整个页面上的坐标是（e.clientX，e.clientY）
    // 鼠标点击的位置在图片的位置坐标为（X1，Y1）
  }

  function dragmove(){
    console.log(this, '===========打印的 ------ dragmove');
  }

  function drop(e) {
    if (e.type === 'drop'){
      e = event ? event : e
      e.preventDefault()
    } else {
      if (event.touches) {
        e = event.touches[0] ? event.touches[0]:event;
      }
    }
    console.log(e);
    dance.style.left = e.clientX - dragOffset.X1 + 'px'
    dance.style.top = e.clientY - dragOffset.Y1 + 'px'
    // 根据鼠标点击的位置在整个页面上的坐标和在图片上的坐标来确定整个图片的坐标
  }


  function allowDrop(e) {
    e = event ? event : e
    // 移动过程中触发
  }

  document.ondragover = function () {
    //取消事件的默认行为
    return false;
  }
  document.ondrop = function () {
    //取消事件的默认行为
    return false
  }
</script>

</body>
</html>
